import axios from "axios";
import { message } from "antd";
import history from "./history";
//基地址与超时
export const baseURL = "http://geek.itheima.net";
const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
});

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("geek_pc");
    //有token添加token
    if (token) config.headers.Authorization = "Bearer " + token;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
//响应拦截器
instance.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    //token过期了
    if (error.response.status === 401) {
      message.error("登录已过期,请重新登录", 1);
      localStorage.removeItem("geek_pc");
      history.push("/Login");
    }
    return Promise.reject(error);
  }
);

export default instance;
